package mysql.ddl;

import com.google.common.base.Joiner;
import mysql.ColumnDefinition;
import mysql.MySQL;
import mysql.Table;
import mysql.commands.SqlCommand;

import mysql.Connection;
import mysql.types.Type;

import java.util.ArrayList;
import java.util.List;

import static mysql.ddl.SqlStrategy.DO_NOTHING;

/**
 * Created by nuno-rafael-figueiredo on 01-07-2014.
 */
public class AlterTable extends SqlCommand{
    private List<AlterSpecification> alterSpecifications = new ArrayList<>();

    private Table table;

    public AlterTable(Connection connection, Table table) {
        super(connection, DO_NOTHING);
        this.table = table;
    }

    public AlterTable addColumn(String name, Type type) {
        alterSpecifications.add(new AddColumn(new ColumnDefinition(name, type)));

        return this;
    }

    private class AlterSpecification {
    }

    public class AddColumn extends AlterSpecification {
        private final ColumnDefinition columnDefinition;
        private final Position position;

        public AddColumn(ColumnDefinition columnDefinition) {
            this(columnDefinition, null);
        }

        public AddColumn(ColumnDefinition columnDefinition, Position position) {
            this.columnDefinition = columnDefinition;
            this.position = position;
        }

        @Override
        public String toString() {
            return Joiner
                    .on(" ")
                    .skipNulls()
                    .join(
                            "ADD COLUMN",
                            columnDefinition,
                            position != null ? position : null
                    );
        }

        public class Position {
            public final Position first = new Position(){
                @Override
                public String toString() {
                    return "FIRST";
                }
            };

            private Position() {
            }
        }

        public class After extends Position{
            private ColumnDefinition columnDefinition;

            private After(ColumnDefinition columnDefinition) {
                this.columnDefinition = columnDefinition;
            }

            @Override
            public String toString() {
                return "AFTER " + MySQL.wrap(columnDefinition.getName());
            }
        }
    }

    @Override
    public String getSql() {
        return String.format("ALTER TABLE %s\n%s",
                table.qualify(),
                Joiner.on(",\n").join(alterSpecifications)
        );
    }
}
